/**
 * @author		Ben Layet
 * @version 	1.0
 * @date		25 Sep 2008
 */
package org.ignoramus.application.store;

import java.util.Iterator;
import java.util.Map;

import org.ignoramus.application.model.CardFactory;
import org.ignoramus.application.model.CardTemplate;
import org.ignoramus.application.model.Lesson;
import org.ignoramus.application.model.ReviewCardImpl;
import org.ignoramus.application.model.StudyEventsLog;

/**
 * Responsible for creating a Lesson form a store.
 */
public class LessonBuilder
{
	/**
	 * Creates a lesson from a store.
	 * @param store the lesson store.
	 * @return a new lesson.
	 * @throws StoreException if a problem occurs while parsing.
	 */
	public Lesson createLesson(LessonStore store) throws StoreException
	{
		//the return value
		Lesson lesson = new Lesson(store.getTitle());
		
		//get the template
		CardTemplate template = new TemplateParser(store.getTemplateData()).getTemplate();
		
		//create the card factory
		CardFactory factory = new CardFactory(template);
		
		//get the cards
		Map<String, Map<String, String>> cards = new CardsParser(store.getCardsData()).getCards();
		//get the log
		Map<String, StudyEventsLog> logs = new LogParser(store.getLogData()).getLogs();
		
		//loop through the cards
		for (Iterator<String> iterator = cards.keySet().iterator(); iterator.hasNext();)
		{
			//get the card id
			String cardId =  iterator.next();
			//get the card info
			Map<String, String> cardContent =  cards.get(cardId);
			
			//review card
			ReviewCardImpl card = (ReviewCardImpl) factory.createReviewCard(cardContent);

			//get the study log
			StudyEventsLog log = logs.get(cardId);
			if(null == log)
			{
				log = new StudyEventsLog();
			}
			//add the log
			card.addAllEvents(log);
			
			//add the card to the lesson
			lesson.put(cardId, card);
			
		}
		//return the lesson
		return lesson;
	}
}